package com.example.androidtest1.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.example.androidtest1.R;
import com.example.androidtest1.bean.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyAdapter extends BaseAdapter {
    private List<User> lists = new ArrayList<User>();
    private Map<Integer, Boolean> isCheck = new HashMap<Integer, Boolean>();
    private Context content = null;

    public MyAdapter(Context content) {
        this.content = content;
        initCheck(false);
    }
    //默认不选中
    public void initCheck(boolean flag) {
        for (int i = 0; i < lists.size(); i++) {
            isCheck.put(i, flag);
        }
    }
    //设置数据
    public void setData(List<User> data) {
        this.lists = data;
    }

    //添加数据
    public void addData(User user) {
        lists.add(user);
    }

    //返回lists长度
    @Override
    public int getCount() {
        return lists != null ? lists.size() : 0;
    }

    //获取选中的item项
    @Override
    public Object getItem(int position) {
        return lists.get(position);
    }

    //获取选中项的id号
    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        ViewHolder holder = null;
        if (convertView == null) {
            view = LayoutInflater.from(content).inflate(R.layout.myadapter_layout, null);
            holder = new ViewHolder();
            holder.textView = view.findViewById(R.id.adapter_tv1);
            holder.checkBox = view.findViewById(R.id.adapter_check1);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (ViewHolder) view.getTag();
        }

        User user = lists.get(position);
        holder.textView.setText(user.getName().toString());
        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isCheck.put(position, isChecked);
            }
        });
        if (isCheck.get(position) == null) {
            isCheck.put(position, false);
        }
        holder.checkBox.setChecked(isCheck.get(position));
        return view;
    }

    public static class ViewHolder {
        public TextView textView;
        public CheckBox checkBox;
    }

    // 全选按钮获取状态
    public Map<Integer, Boolean> getMap() {
    // 返回状态
        return isCheck;
    }

    // 删除一个数据
    public void removeData(int position) {
        lists.remove(position);
    }
}
